/**************************************************************

Copyright Astrium Services GEO-Information / Spot Image
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

 ***************************************************************/
package com.spotimage.catalog.client.util;

import java.util.Date;

import com.google.gwt.core.client.GWT;
import com.google.gwt.i18n.client.DateTimeFormat;

/**
 * Various useful methods
 */
public class Util {
	
	/** ISO8601 date format */
	public static final String ISO8601_FORMAT = "yyyy-MM-dd'T'HH:mm:ss'Z'";
	/** date format */
	private static final DateTimeFormat dateFormatter = DateTimeFormat.getFormat("dd/MM/yyyy");

	/**
	 * Get application image URL from file name.
	 * @param image
	 * @return
	 */
	public static String getImageUrl(String image) {
		return GWT.getModuleBaseURL() + "images/" + image;
	}

	/**
	 * Get {@link java.util.Date} from ISO 8601 date string.
	 * @param iso
	 * @return
	 */
	public static Date getDateFromISO8601(String iso) {
		DateTimeFormat dateFormatter = DateTimeFormat.getFormat(ISO8601_FORMAT);
		return dateFormatter.parse(iso);
	}
	
	/**
	 * Get ISO 8601 date string from {@link java.util.Date}.
	 * @param iso
	 * @return
	 */
	public static String getISO8601FromDate(Date date) {
		DateTimeFormat dateFormatter = DateTimeFormat.getFormat(ISO8601_FORMAT);
		return dateFormatter.format(date);
	}
	
	/**
	 * Get formatted ("dd/MM/yyyy") date string from {@link java.util.Date}.
	 * @param date
	 * @return
	 */
	public static String getDateString(Date date) {
		return dateFormatter.format(date);
	}

	/**
	 * Global date formatter.
	 * @return
	 */
	public static DateTimeFormat getDateFormatter() {
		return dateFormatter;
	}
	
	/**
	 * Format a double to {@link String} for display.
	 */
	public static String getFormattedCoordinate(double d) {
		String s = Double.toString(d); 
		int decimals = 4;
		int idx = s.indexOf('.');
		if (idx != -1 && idx < s.length() - decimals) s = s.substring(0, idx + decimals + (decimals==0 ? 0 : 1));
		while ((s.substring(idx, s.length())).length() <= decimals) {
			s += "0"; 
			idx = s.indexOf('.');
		}
		return s;
	}
	
}
